package com.ruoyix.im.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.ChainWrappers;
import com.ruoyix.common.core.domain.PageQuery;
import com.ruoyix.common.core.domain.R;
import com.ruoyix.common.core.domain.entity.SysUser;
import com.ruoyix.common.core.page.TableDataInfo;
import com.ruoyix.common.helper.LoginHelper;
import com.ruoyix.common.utils.StringUtils;

import com.ruoyix.im.domain.ImChatGroup;
import com.ruoyix.im.domain.ImChatGroupUser;
import com.ruoyix.im.domain.ImChatUserGroupMessage;
import com.ruoyix.im.domain.bo.ImChatUserGroupMessageBo;
import com.ruoyix.im.domain.vo.GroupMessageVO;
import com.ruoyix.im.domain.vo.ImChatUserGroupMessageVo;
import com.ruoyix.im.mapper.ImChatGroupMapper;
import com.ruoyix.im.mapper.ImChatGroupUserMapper;
import com.ruoyix.im.mapper.ImChatUserGroupMessageMapper;
import com.ruoyix.im.service.IImChatGroupService;
import com.ruoyix.im.service.IImChatGroupUserService;
import com.ruoyix.im.service.IImChatUserGroupMessageService;
import com.ruoyix.im.websocket.ImConfigConst;
import com.ruoyix.system.mapper.SysUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 群聊记录Service业务层处理
 *
 * @author ruoyi
 * @date 2024-05-27
 */
@RequiredArgsConstructor
@Service
public class ImChatUserGroupMessageServiceImpl extends ServiceImpl<ImChatUserGroupMessageMapper, ImChatUserGroupMessage> implements IImChatUserGroupMessageService {

    private final ImChatUserGroupMessageMapper baseMapper;
    private final ImChatGroupMapper imChatGroupMapper;
    private final ImChatGroupUserMapper imChatGroupUserMapper;
    private final SysUserMapper sysUserMapperl;

    /**
     * 查询群聊记录
     */
    @Override
    public ImChatUserGroupMessageVo queryById(Long id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询群聊记录列表
     */
    @Override
    public TableDataInfo<ImChatUserGroupMessageVo> queryPageList(ImChatUserGroupMessageBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<ImChatUserGroupMessage> lqw = buildQueryWrapper(bo);
        Page<ImChatUserGroupMessageVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询群聊记录列表
     */
    @Override
    public List<ImChatUserGroupMessageVo> queryList(ImChatUserGroupMessageBo bo) {
        LambdaQueryWrapper<ImChatUserGroupMessage> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<ImChatUserGroupMessage> buildQueryWrapper(ImChatUserGroupMessageBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<ImChatUserGroupMessage> lqw = Wrappers.lambdaQuery();
        lqw.eq(bo.getGroupId() != null, ImChatUserGroupMessage::getGroupId, bo.getGroupId());
        lqw.eq(bo.getFromId() != null, ImChatUserGroupMessage::getFromId, bo.getFromId());
        lqw.eq(bo.getToId() != null, ImChatUserGroupMessage::getToId, bo.getToId());
        lqw.eq(StringUtils.isNotBlank(bo.getContent()), ImChatUserGroupMessage::getContent, bo.getContent());
        return lqw;
    }

    /**
     * 新增群聊记录
     */
    @Override
    public Boolean insertByBo(ImChatUserGroupMessageBo bo) {
        ImChatUserGroupMessage add = BeanUtil.toBean(bo, ImChatUserGroupMessage.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改群聊记录
     */
    @Override
    public Boolean updateByBo(ImChatUserGroupMessageBo bo) {
        ImChatUserGroupMessage update = BeanUtil.toBean(bo, ImChatUserGroupMessage.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ImChatUserGroupMessage entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除群聊记录
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    public R<Page> getPagePoetryResult(Long current, Long size, Long groupId) {
        Page<ImChatUserGroupMessage> page = new Page<>();
        page.setCurrent(current);
        page.setSize(size);

        Long userId = LoginHelper.getUserId();

        ImChatGroup chatGroup = imChatGroupMapper.selectById(groupId);
        if (chatGroup == null) {
            return R.fail("群组不存在！");
        }

        if (chatGroup.getGroupType().intValue() == ImConfigConst.GROUP_COMMON) {
            LambdaQueryChainWrapper<ImChatGroupUser> groupLambdaQuery = ChainWrappers.lambdaQueryChain(imChatGroupUserMapper, ImChatGroupUser.class);
            groupLambdaQuery.eq(ImChatGroupUser::getGroupId, groupId);
            groupLambdaQuery.eq(ImChatGroupUser::getUserId, userId);
            groupLambdaQuery.in(ImChatGroupUser::getUserStatus, ImConfigConst.GROUP_USER_STATUS_PASS, ImConfigConst.GROUP_USER_STATUS_SILENCE);
            Long count = groupLambdaQuery.count();
            if (count < 1) {
                return R.fail("未加群！");
            }
        }

        LambdaQueryChainWrapper<ImChatUserGroupMessage> lambdaQuery = lambdaQuery();
        lambdaQuery.eq(ImChatUserGroupMessage::getGroupId, groupId);
        lambdaQuery.orderByDesc(ImChatUserGroupMessage::getCreateTime);
        Page<ImChatUserGroupMessage> result = lambdaQuery.page(page);
        List<ImChatUserGroupMessage> records = result.getRecords();
        Collections.reverse(records);
        if (CollectionUtils.isEmpty(records)) {
            return R.ok(result);
        } else {
            List<GroupMessageVO> collect = records.stream().map(message -> {
                GroupMessageVO groupMessageVO = new GroupMessageVO();
                groupMessageVO.setContent(message.getContent());
                groupMessageVO.setFromId(message.getFromId());
                groupMessageVO.setToId(message.getToId());
                groupMessageVO.setId(message.getId());
                groupMessageVO.setGroupId(message.getGroupId());
                groupMessageVO.setCreateTime(message.getCreateTime());
                Long messageUserId = message.getFromId();
                SysUser user = sysUserMapperl.selectUserById(messageUserId);
                if (user != null) {
                    groupMessageVO.setUsername(user.getUserName());
                    groupMessageVO.setAvatar(user.getAvatar());
                }
                return groupMessageVO;
            }).collect(Collectors.toList());
            Page<GroupMessageVO> resultVO = new Page<>();
            resultVO.setRecords(collect);
            resultVO.setTotal(result.getTotal());
            resultVO.setCurrent(result.getCurrent());
            resultVO.setSize(result.getSize());
            return R.ok(resultVO);
        }
    }
}
